import { StorageKey, EventKey } from '../common/Key';
import { TestLevel } from '../game/GameDefine';
const RecoverTime = 600;
const MaxEnergy = 10;
export const EnergyMgr = {
    energy: MaxEnergy,
    countDown: RecoverTime,

    init() {
        this.energyFull = false;
        this._getOutLineEnergy();

        G.utils.schedule(() => {
            this._saveData();
        }, 10)

        G.utils.schedule(() => {
            if (this.energyFull) {
                return;
            }
            this.countDown--;
            if (this.countDown <= 0) {
                this.countDown = RecoverTime;
                this.addEnergy(true);
                this._saveData();
            }
            G.onFire.fire(EventKey.EVENT_TIME_CHANGE);
        }, 1)
    },

    _getOutLineEnergy() {
        let param = G.data.getItem(StorageKey.OUT_LINE_TIME, {
            energy: this.energy,
            countDown: this.countDown,
            time: Date.now()
        });

        let recoverEnergy = 0;
        let outTime = Math.floor((Date.now() - param.time) / 1000);
        if (outTime <= 0) {
            recoverEnergy = 0;
        } else {
            recoverEnergy += Math.floor(outTime / RecoverTime);
            this.countDown = param.countDown - outTime % RecoverTime;
        }

        let allEnergy = param.energy + recoverEnergy;
        if (allEnergy >= MaxEnergy) {
            this.energyFull = true;
            allEnergy = MaxEnergy;
            this.countDown = RecoverTime;
        }
        this.energy = allEnergy;
        this._saveData();
    },

    addEnergy(auto = false) {
        if (this.energy >= MaxEnergy) {
            if (!auto) {
                G.game.toast('能量已满', 0.5);
            }
            return false;
        }
        this.energy++;
        if(this.energy >= MaxEnergy){
            this.energyFull = true;
            this.countDown = RecoverTime;
        }
        G.onFire.fire(EventKey.EVENT_ENERGY_CHANGE);
        return true;
    },

    subEnergy() {
        if(TestLevel){
            return true;
        }
        if (this.energy <= 0) {
            return false;
        }
        this.energy--;
        this.energyFull = false;
        this._saveData();
        G.onFire.fire(EventKey.EVENT_ENERGY_CHANGE);
        return true;
    },

    getFormatCountDown() {
        let countDown = this.countDown;
        if (this.energyFull) {
            return '';
        }
        let m = Math.floor(countDown / 60);
        let s = countDown % 60;
        return `${G.utils.prefixZero(m, 2)}:${G.utils.prefixZero(s, 2)}`;
    },

    getFormatEnergy() {
        return `${this.energy}/${MaxEnergy}`;
    },

    _saveData() {
        let param = {
            energy: this.energy,
            countDown: this.countDown,
            time: Date.now()
        }
        G.data.setItem(StorageKey.OUT_LINE_TIME, param);
    },
}